package jym.tan.movielibrary.tmdb;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;

import jym.tan.movielibrary.constant.GlobalConstant;
import jym.tan.movielibrary.dto.MovieSearch;
import jym.tan.movielibrary.json.JsonParser;
import jym.tan.movielibrary.url.URLHandler;
import jym.tan.movielibrary.utils.MovieTitleUtils;
import jym.tan.movielibrary.utils.PropertiesUtils;


public class Movie {

	public static class Search {

		private static class LazySearch {
			private static final Search SEARCH;
			
			static {
				SEARCH = new Search();
			}
		}
		
		public static Search getInstance() {
			return Search.LazySearch.SEARCH;
		}
		
		public String getURL(String name) {
			String movieSearchURL = PropertiesUtils.getMovieSearchURL();
			String apiKey = ApiKey.getInstance().getApiKey();
			String urlSeparator = GlobalConstant.URL_SEPERATOR;
			StringBuilder builder = new StringBuilder();
			builder.append(movieSearchURL).append(urlSeparator).append(apiKey).append(urlSeparator).append(MovieTitleUtils.getProperName(name));			
			return builder.toString();
		}
		
		public Object getMovieSearchResult(String name) {
			String jsonString = null;
			MovieSearch[] movieSearches = null;
			try {
				jsonString = URLHandler.getInstance().getJsonStringFromURL(getURL(name));
			} catch (IOException e) {
				return null;
			}
			
			if(StringUtils.isNotBlank(jsonString)) {
				movieSearches = JsonParser.getInstance().convertJsonToObject(jsonString, MovieSearch[].class);	
			}
			
			return (movieSearches != null) ? movieSearches : Integer.valueOf(0);
		}
	}	
}
